package main

import(
	"fmt"
	"time"
	"github.com/samuel/go-zookeeper/zk"
)

func ZkStateStringFormat(s *zk.Stat) string { 
	return fmt.Sprintf("Czxid:%d\nMzxid: %d\nCtime: %d\nMtime: %d\nVersion: %d\nCversion: %d\nAversion: %d\nEphemeralOwner: %d\nDataLength: %d\nNumChildren: %d\nPzxid: %d\n", 
		s.Czxid, s.Mzxid, s.Ctime, s.Mtime, s.Version, s.Cversion, s.Aversion, s.EphemeralOwner, s.DataLength, s.NumChildren, s.Pzxid) 
}



func main(){
	fmt.Println("zookeeper basic test begin>>>>>>>>>>>>");
	hosts := []string{"127.0.0.1:2181"}; 

	conn, _, err := zk.Connect(hosts, time.Second*5);
	if(err != nil){
		fmt.Println("zk connect failed, caused by " + err.Error());
		return
	}
	defer conn.Close();

	var path = "/zk_test_go" ;
	var data = []byte("hello") ;
	var flags int32 = 0 ;// permission 
	var acls = zk.WorldACL(zk.PermAll);
	res, err := conn.Create(path, data, flags, acls);
	if(err != nil){
		fmt.Println("zk create failed, caused by " + err.Error());
		return
	}
	fmt.Println("create " + res);

	exist, stat, err := conn.Exists(path);
	if(err != nil){
		fmt.Println("zk Exists failed, caused by " + err.Error());
		return
	}
	fmt.Printf("%s exist is %t/n", path, exist);
	fmt.Printf("state: %s/n", ZkStateStringFormat(stat));
	
	// update 
	var new_data = []byte("zk_test_new_value") 
	stat, err = conn.Set(path, new_data, stat.Version) 
	if err != nil { 
		fmt.Println("zk Set failed, caused by " + err.Error());
		return 
	} 
	fmt.Printf("update state:\n") 
	fmt.Printf("%s\n", ZkStateStringFormat(stat))

	dataByte, stat, err := conn.Get(path);
	if(err != nil){
		fmt.Println("zk get failed, caused by " + err.Error());
		return
	}
	fmt.Printf("%s data is %s/n", path, string(dataByte));
	fmt.Printf("state: %s/n", ZkStateStringFormat(stat));

	// delete 
	err = conn.Delete(path, stat.Version) 
	if err != nil {
		fmt.Println("zk Delete failed, caused by " + err.Error());
		return 
	} 
	// check exist 
	exist, stat, err = conn.Exists(path) 
	if err != nil { 
		fmt.Println("zk Exists failed, caused by " + err.Error());
		return 
	} 
	fmt.Printf("after delete, path[%s] exist[%t]\n", path, exist) 
	fmt.Printf("state:\n") 
	fmt.Printf("%s\n", ZkStateStringFormat(stat))

	fmt.Println("zookeeper basic test end>>>>>>>>>>>>");
}

